import React from "react";
import {
  Form,
  Input,
  Select,
  Button,
  Spin,
  Modal,
  List,
  Card,
  Space,
  Breadcrumb,
  DatePicker,
  Tooltip,
  message,
  Popconfirm,
  Drawer,
  Upload,
} from "antd";
import {
  DeleteOutlined,
  QuestionCircleOutlined,
  QrcodeOutlined,
  FormOutlined,
  ExclamationCircleOutlined,
  ApiOutlined,
  UploadOutlined,
} from "@ant-design/icons";
import { Link } from "react-router-dom";
import { connect } from "react-redux";

import "./exp.css";

import {
  _selTchExping,
  _updateExp,
  _endExp,
  _delExp,
  _selExpAllMark,
} from "../../../../utils/exp/index";
import { _getClassList } from "../../../../utils/class/idnex";

const { Option } = Select;
const { TextArea } = Input;

const { confirm } = Modal;
const { RangePicker } = DatePicker;

class Index extends React.Component {
  formRef = React.createRef();

  state = {
    isLoading: false,
    isDLoading: false,
    className: [],
    exp_num: "",
    data: [],
    e_visible: false,
    exp_data: {},
  };
  editSource = (val) => {
    console.log(val);
    this.setState({
      e_visible: true,
      exp_data: val,
    });
    _getClassList().then((res) => {
      this.setState({ className: res.data.data });
    });
  };
  onFinish = (val) => {
    // console.log("Received values of form: ", val);
    this.formRef.current.resetFields();
    this.formRef.current.setFieldsValue(val);
    let tempData = {
      exp_name: val.exp_name,
      exp_grade: val.exp_grade,
      exp_class: val.exp_class,
      exp_msg: val.exp_msg,
      exp_time: `${val["range-picker"][0].format("YYYY-MM-DD")} 至 ${val[
        "range-picker"
      ][1].format("YYYY-MM-DD")}`,
    };
    if (!val.exp_word) {
      tempData.exp_word = this.state.exp_data.exp_word;
    } else {
      tempData.exp_word = val.exp_word.fileList[0].response.data.data.filename;
    }
    if (!val.exp_fj) {
      tempData.exp_fj = this.state.exp_data.exp_fj;
    } else {
      tempData.exp_fj = val.exp_fj.fileList[0].response.data.data.filename;
    }
    this.setState({ isDLoading: true });

    _updateExp(this.state.exp_data.exp_id, tempData)
      .then((res) => {
        if (res.status === 200 && res.data.code === 0) {
          this.setState({ isDLoading: false });
          this.getData();
          message.success("实验信息更新成功", 1.5).then(() => {
            this.setState({ e_visible: false });
          });
        }
      })
      .catch(() => {
        this.setState({ isDLoading: false });
        message.error("服务器错误");
      });
  };
  handleCancel = () => {
    this.setState({
      e_visible: false,
    });
  };

  componentDidMount = () => {
    this.getData();
  };
  getData = () => {
    // console.log(this.props.state.data.tch_id);
    // console.log("search:", val);
    this.setState({ isLoading: true });
    _selTchExping(this.props.state.data.tch_id)
      .then((res) => {
        if (res.status === 200 && res.data.code === 0) {
          this.setState({ isLoading: false });
          this.setState({
            data: res.data.data,
          });
        }
      })
      .catch(() => {
        this.setState({ isLoading: false });
        message.error("服务器错误");
      });
  };
  // 结束实验
  endExp = (val) => {
    let self = this;
    confirm({
      title: "你确定要结束该实验吗？",
      okText: "确定",
      cancelText: "取消",
      icon: <ExclamationCircleOutlined />,
      content: `实验名称：${val.exp_name}`,
      onOk() {
        self.setState({ isLoading: true });

        _selExpAllMark(val.exp_id).then((res) => {
          if (res.status === 200 && res.data.code === 0) {
            self.setState({ isLoading: false });
            let arr = res.data.data;
            let len = arr.length;
            // console.log(arr);
            if (!len) {
              message.info("同学还未选课，无法结束");
              return;
            }
            let is_end = false;

            for (let i = 0; i < len; i++) {
              if (!arr[i].exp_mark) {
                message.warning("还有实验未批阅，无法结束该实验");
                return;
              } else {
                is_end = true;
              }
            }

            if (is_end) {
              _endExp(val.exp_id)
                .then((res) => {
                  if (res.status === 200 && res.data.code === 0) {
                    message.success(`${val.exp_name} 实验结束成功`, 2);
                    self.getData();
                  }
                })
                .catch(() => {
                  self.setState({ isLoading: false });

                  message.error("服务器错误");
                });
            }
          }
        });
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };
  //删除实验
  deletSource = (val) => {
    _delExp(val)
      .then((res) => {
        if (res.status === 200 && res.data.code === 0) {
          message.success("删除成功");
          this.getData();
        }
      })
      .catch(() => {
        this.setState({ isLoading: false });
        message.error("服务器错误");
      });
  };
  render() {
    let expData = this.state.exp_data;
    const layout = {
      labelCol: {
        span: 4,
      },
      wrapperCol: {
        span: 10,
      },
    };
    const tailLayout = {
      wrapperCol: {
        offset: 4,
        span: 16,
      },
    };

    const rangeConfig = {
      rules: [
        {
          type: "array",
          required: true,
          message: "Please select time!",
        },
      ],
    };
    return (
      <div>
        <div className="stu-header">
          <Breadcrumb style={{ margin: "16px 0" }}>
            <Breadcrumb.Item>实验(进行中)</Breadcrumb.Item>
          </Breadcrumb>
        </div>

        <div className="admin-body" style={{ padding: 15, minHeight: 360 }}>
          <Spin tip="Loading..." spinning={this.state.isLoading}>
            <List
              grid={{
                gutter: 16,
                xs: 1,
                sm: 2,
                md: 2,
                lg: 3,
                xl: 3,
                xxl: 4,
              }}
              pagination={{
                onChange: (page) => {
                  console.log(page);
                },
                pageSize: 6,
              }}
              dataSource={this.state.data}
              renderItem={(v) => (
                <List.Item>
                  <Card
                    title={
                      <Tooltip title={v.exp_msg}>
                        <div className="card-header">
                          {v.exp_name}

                          <p>（{v.exp_class}）</p>
                        </div>
                      </Tooltip>
                    }
                    bordered={false}
                    extra={
                      <Space>
                        <FormOutlined
                          style={{ color: "#f6f6f6" }}
                          onClick={this.editSource.bind(this, v)}
                        />
                        <Popconfirm
                          title="确认要删除该实验吗？"
                          okText="是"
                          cancelText="否"
                          onConfirm={this.deletSource.bind(this, v.exp_id)}
                        >
                          <DeleteOutlined style={{ color: "#f6f6f6" }} />
                        </Popconfirm>
                      </Space>
                    }
                    headStyle={{
                      background: `${v.exp_style}`,
                      fontSize: "16px",
                      color: "#f6f6f6",
                      boxShadow: "5px 7px 23px 0px rgba(58, 52, 82, 0.16)",
                      borderTopLeftRadius: "5px",
                      borderTopRightRadius: "5px",
                    }}
                    bodyStyle={{
                      padding: "10px",
                      boxShadow: "5px 7px 23px 0px rgba(58, 52, 82, 0.16)",
                      borderBottomLeftRadius: "5px",
                      borderBottomRightRadius: "5px",
                    }}
                  >
                    <div className="card-body">
                      <Link to={{ pathname: "/admin/t-e-d", state: v }}>
                        <div>
                          <span>年级：</span>
                          {v.exp_grade}
                        </div>

                        <div>
                          <span>专业：</span>
                          {v.exp_class}
                        </div>
                        <div>
                          <span>实验时间：</span>
                          {v.exp_time}
                        </div>
                      </Link>
                      <div className="card-footer">
                        <div>
                          <Space size="large">
                            <Space>
                              <QrcodeOutlined
                                style={{ color: "#1890ff", fontSize: 14 }}
                              />
                              {v.exp_num}
                            </Space>
                          </Space>
                        </div>
                        <div
                          onClick={this.endExp.bind(this, v)}
                          className="exp-join"
                        >
                          <Space>
                            <ApiOutlined
                              style={{ color: "#1890ff", fontSize: 14 }}
                            />
                            结束
                          </Space>
                        </div>
                      </div>
                    </div>
                  </Card>
                </List.Item>
              )}
            />
          </Spin>
          <Drawer
            placement="left"
            closable={false}
            onClose={this.handleCancel}
            visible={this.state.e_visible}
            key="left"
            width={"50vw"}
          >
            <Spin tip="Loading..." spinning={this.state.isDLoading}>
              <Form
                {...layout}
                ref={this.formRef}
                name="control-ref"
                initialValues={{
                  remember: true,
                }}
                onFinish={this.onFinish}
                initialValues={{
                  exp_name: expData.exp_name,
                  exp_grade: expData.exp_grade,
                  exp_class: expData.exp_class,
                  exp_msg: expData.exp_msg,
                }}
              >
                <Form.Item
                  label="实验名称"
                  name="exp_name"
                  rules={[
                    {
                      required: true,
                      message: "请输入实验名称!",
                    },
                  ]}
                >
                  <Input />
                </Form.Item>

                <Form.Item
                  label="年级"
                  name="exp_grade"
                  rules={[
                    {
                      required: true,
                      message: "请输入年级!",
                    },
                  ]}
                >
                  <Input
                    placeholder="如2019级"
                    defaultValue={expData.exp_grade}
                  />
                </Form.Item>
                <Form.Item
                  label="专业班级"
                  name="exp_class"
                  rules={[
                    {
                      required: true,
                      message: "请选择专业班级!",
                    },
                  ]}
                >
                  <Select
                    showSearch
                    style={{ width: "180px" }}
                    placeholder="专业班级"
                    optionFilterProp="children"
                    defaultValue={expData.exp_class}
                    filterOption={(input, option) =>
                      option.children
                        .toLowerCase()
                        .indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    {this.state.className.map((v) => (
                      <Option value={v.class_name} key={v.class_id}>
                        {v.class_name}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
                <Form.Item
                  label="描述"
                  name="exp_msg"
                  rules={[
                    {
                      required: true,
                      message: "请添加描述信息!",
                    },
                  ]}
                >
                  <TextArea
                    rows={4}
                    placeholder="简单描述一下实验吧"
                    defaultValue={expData.exp_msg}
                  />
                </Form.Item>
                <Form.Item
                  name="range-picker"
                  label="实验时间"
                  {...rangeConfig}
                >
                  <RangePicker />
                </Form.Item>
                <Form.Item
                  label={
                    <span>
                      实验报告&nbsp;
                      <Tooltip title="如无文件信息无更改，可不上传">
                        <QuestionCircleOutlined />
                      </Tooltip>
                    </span>
                  }
                  name="exp_word"
                >
                  <Upload
                    name="file"
                    action="/api/up_word"
                    listType="text"
                    onChange={this.onFileChange}
                    accept=".docx"
                    disabled={false}
                  >
                    <Button>
                      <UploadOutlined /> 点击上传
                    </Button>
                  </Upload>
                </Form.Item>
                <Form.Item
                  label={
                    <span>
                      附件&nbsp;
                      <Tooltip title="如无文件信息无更改，可不上传">
                        <QuestionCircleOutlined />
                      </Tooltip>
                    </span>
                  }
                  name="exp_fj"
                >
                  <Upload
                    name="file"
                    action="/api/up_fj"
                    listType="text"
                    onChange={this.onFileChange}
                  >
                    <Button>
                      <UploadOutlined /> 点击上传
                    </Button>
                  </Upload>
                </Form.Item>

                <Form.Item {...tailLayout}>
                  <Button type="primary" htmlType="submit">
                    修改
                  </Button>
                </Form.Item>
              </Form>
            </Spin>
          </Drawer>
        </div>
      </div>
    );
  }
}
const mapStateToProps = (state) => {
  return {
    state: state.user,
  };
};
const actionCreator = {};
export default connect(mapStateToProps, actionCreator)(Index);
